import 'whatwg-fetch';
import 'custom-event-polyfill';
import 'core-js/stable/promise';
import 'core-js/stable/symbol';
import 'core-js/stable/string/starts-with';
import 'core-js/web/url';
import 'react-app-polyfill/ie11';

import { dynamic, history } from 'umi';
import { getAppMenuTree } from '@/servers/common';
import { ImuneTreeArr } from '@/types/common';

// 判断有无token -- 模拟登录
if(window.localStorage.getItem('token')){
    history.push('/Home');
}
else{
    history.push('/');
}

/**
 * 窗口离开的时候
 */
window.onbeforeunload = () => {
    // 获取打开个数
    let numbers = window.localStorage.getItem('numbers');
    // 第一个标签页打开的时间
    const sesTime = window.sessionStorage.getItem('sesTime');
    const localTime = window.localStorage.getItem('localTime');

    //当 sesTime === localTime，减去当前页。
    if (localTime && localTime && sesTime === localTime) {
        numbers = parseInt(numbers) - 1;
        window.localStorage.setItem('numbers', numbers)
    }
};

/**
 * 页面加载的时候触发
 */
window.onload = () => {
    let time = '';
    // 计算打开的标签页数量
    let numbers = window.localStorage.getItem('numbers');
    const sesTime = window.sessionStorage.getItem('sesTime');
    // 首次登录的时间
    const localTime = window.localStorage.getItem('localTime');
    // 当numbers无值或者小于0时，为numbers 赋值0
    if (numbers == 'NaN' || numbers === null || parseInt(numbers) < 0) {
        numbers = 0;
    }
    // sesTime || localTime 没有值，并且numbers为0时，清除localStorage里的登录状态，退出到登录页面
    if ((sesTime === null || sesTime === 'NaN' || localTime === null ||
        localTime === 'NaN') && parseInt(numbers) === 0) {
        localStorage.clear();
        sessionStorage.clear();
        //为localTime和sesTime赋值，记录第一个标签页的时间
        time = new Date().getTime();
        window.sessionStorage.setItem('sesTime', time);
        window.localStorage.setItem('localTime', time);

        history.push('/');
    }
    // 当time ，localTime 有值，并且sesTime != localTime时，为sesTime赋值
    if (!time && localTime != 'NaN' && localTime != null && sesTime != localTime) {
        window.sessionStorage.setItem('sesTime', localTime);
    }
    // 最后保存当前是第几个标签页
    numbers = parseInt(numbers) + 1;
    window.localStorage.setItem('numbers', numbers);
};












// 当前用户所属权限路由
let permissionsRoutes: ImuneTreeArr[] = [];

// 动态添加基座路由
const routerList = [
    {
        name: '用户管理',
        icon: 'smile',
        path: '/wanfeng',
        redirect: '/wanfeng/userAdmin', // 首页默认就是用户管理
        component: dynamic({
            loader: () => import('@/pages/authority/UserList/index'),
        }),
    },
    {
        name: '用户管理',
        icon: 'smile',
        path: '/wanfeng/userAdmin',
        component: dynamic({
            loader: () => import('@/pages/authority/UserList/index'),
        }),
    },
    {
        name: '应用管理',
        icon: 'smile',
        path: '/wanfeng/appList',
        component: dynamic({
            loader: () => import('@/pages/authority/AppList/index'),
        }),
    },
    {
        name: '公共页面',
        icon: 'smile',
        path: '/wanfeng/publicApp',
        component: dynamic({
            loader: () => import('@/pages/authority/PublicApp/index'),
        }),
    }
];

// 请求服务端根据响应动态更新路由
export function patchRoutes({ routes }: any) {
    // 用户管理
    routes[1].routes.unshift(routerList[0]);
    // 用户管理
    routes[1].routes.unshift(routerList[1]);
    // 应用管理
    routes[1].routes.unshift(routerList[2]);
    // 公共页面
    routes[1].routes.unshift(routerList[3]);


    // 根据查出来的菜单数据 动态添加路由
    if (permissionsRoutes.length > 0) {
        permissionsRoutes.forEach((item: ImuneTreeArr) => {
            if (item.path.split('/')[2] === 'userAdmin') {
                routes[1].routes.unshift({
                    name: item.title,
                    icon: 'smile',
                    path: item.path,
                    component: dynamic({
                        loader: () => import('@/pages/authority/UserList/index'),
                    })
                });
            }
            if (item.path.split('/')[2] === 'appList') {
                routes[1].routes.unshift({
                    name: item.title,
                    icon: 'smile',
                    path: item.path,
                    component: dynamic({
                        loader: () => import('@/pages/authority/AppList/index'),
                    })
                });
            }
            if (item.path.split('/')[2] === 'publicApp') {
                routes[1].routes.unshift({
                    name: item.title,
                    icon: 'smile',
                    path: item.path,
                    component: dynamic({
                        loader: () => import('@/pages/authority/PublicApp/index'),
                    })
                });
            }
            if (item.path.split('/')[2] === 'publicApp2') {
                routes[1].routes.unshift({
                    name: item.title,
                    icon: 'smile',
                    path: item.path,
                    component: dynamic({
                        loader: () => import('@/pages/authority/PublicApp/index'),
                    })
                });
            }
        })
    }
}

// 渲染之前做权限校验，
export async function render(oldRender: any) {
    const res = await getAppMenuTree({});
    console.log(res)
    permissionsRoutes = res.data;


    oldRender();
}
